use tokio::task::JoinSet;
use log::trace;
use crate::task_confs::*;
use crate::task_stat::*;

pub fn run(tc: TaskConfs) {
    tokio::runtime::Builder::new_multi_thread()
        .worker_threads(8)
        .enable_all()
        .build()
        .unwrap()
        .block_on(async move {
            let mut set = JoinSet::new();
            let mut taskstat = TaskStat::new();
            taskstat.init_stat_from_taskconfs(tc);
            for (_, task) in taskstat.taskmap.iter_mut() {
                if task.is_ready() {
                    let t = task.get_clone();
                    set.spawn(async move {
                        t.exec_commands()
                    });
                }
            }

            while let Some(task_name) = set.join_next().await {
                let name = task_name.unwrap();
                trace!("Completed task : {}", name);
                if let Some(depended_names) = taskstat.dependances.get(&name) {
                    for dn in depended_names.iter() {
                        if let Some(task) = taskstat.taskmap.get_mut(dn) {
                            task.decrease();
                            if task.is_ready() {
                                let t = task.get_clone();
                                set.spawn(async move {
                                    t.exec_commands()
                                });
                            }
                        }
                    }
                }
            }
        });
}